package cn.fx.exception;

import cn.fx.exception.enums.GlobalEnum;
import cn.fx.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@Component
@RestControllerAdvice
public class GlobalException {

    // 要捕捉Exception类型的异常
    @ExceptionHandler(Exception.class)
    public JsonResult globalException(Exception e){
        e.printStackTrace();
        log.info("发生了Exception异常！" + e.getMessage());
        return JsonResult.error(GlobalEnum.ERROR);
    }

    // 捕捉自定义异常类型GloobalMadeException
    @ExceptionHandler(GloobalMadeException.class)
    public JsonResult globalException(GloobalMadeException e){
        e.printStackTrace();
        log.info("发生了GloobalMadeException异常！" + e.getErrorMessage() + "--" + e.getErrorCode());
        return JsonResult.error(e);
    }

    // 捕捉自定义异常类型GloobalMadeException
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult globalException(MethodArgumentNotValidException e){
        e.printStackTrace();
        StringBuilder stringBuilder = new StringBuilder();
        e.getBindingResult().getAllErrors().forEach(item->{
            stringBuilder.append(item.getDefaultMessage()).append("，");
        });
        log.info("发生了GloobalMadeException异常！" + stringBuilder.toString());
        return JsonResult.error(stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString(),"10002");
    }
}
